<template>
  <div class="divBox relative">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-tabs v-model="tableFrom.type" @tab-click="seachList">
          <el-tab-pane :label="item.name" :name="item.type.toString()" v-for="(item,index) in headeNum" :key="index"/>
        </el-tabs>
        <div class="container mt-1">
          <el-form inline size="small">
            <el-form-item label="课程分类：">
              <el-cascader v-model="tableFrom.cateId" :options="merCateList" :props="props" clearable
                           class="selWidth mr20" @change="seachList" size="small"
              />
            </el-form-item>
            <el-form-item label="课程搜索：">
              <el-input v-model="tableFrom.name" placeholder="请输入课程名称" class="selWidth" size="small" clearable>
                <el-button slot="append" icon="el-icon-search" @click="seachList" size="small"
                           v-hasPermi="['admin:course:list']"
                />
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-button size="small" type="primary" @click="addCourse" class="mr10" v-hasPermi="['admin:course:save']">添加课程
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        :highlight-current-row="true"
        :header-cell-style=" {fontWeight:'bold'}"
      >
        <el-table-column
          prop="id"
          label="ID"
          min-width="50"
        />
        <el-table-column label="课程名称"
                         prop="name"
                         min-width="150"
                         :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column label="课程封面" min-width="80">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 36px; height: 36px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="副标题"
                         prop="subName"
                         :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="codeCount"
          label="课程码"
          min-width="90"
          align="center"
        />
        <el-table-column
          prop="listCount"
          label="课程数"
          min-width="90"
          align="center"
        />
        <el-table-column
          prop="sort"
          label="排序"
          min-width="70"
          align="center"
        />

        <el-table-column
          label="添加时间"
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
              <span>{{ scope.row.createTime | dataFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          min-width="80"
          fixed="right"
        >
          <template slot-scope="scope"
                    v-if="checkPermi(['admin:product:up','admin:product:down'])"
          >
            <el-switch
              :disabled="Number(tableFrom.type) > 2"
              v-model="scope.row.isShow"
              :active-value="true"
              :inactive-value="false"
              active-text="上架"
              inactive-text="下架"
              @change="onchangeIsShow(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right" align="center">
          <template slot-scope="scope">
            <router-link :to="{path: '/course/detail/' + scope.row.id }">
              <el-button type="text" size="small" class="mr10" v-hasPermi="['admin:product:info']">详情</el-button>
            </router-link>
            <router-link :to="{path: '/course/detail/' + scope.row.id}">
              <el-button type="text" size="small" class="mr10" v-if="scope.row.isShow==false"
                         v-hasPermi="['admin:product:update']"
              >编辑
              </el-button>
            </router-link>
            <el-button v-if="tableFrom.type === '5'" type="text" size="small"
                       @click="handleRestore(scope.row.id, scope.$index)" v-hasPermi="['admin:product:restore']"
            >恢复课程
            </el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row.id, tableFrom.type)"
                       v-hasPermi="['admin:product:delete']"
            >{{ tableFrom.type === '5' ? '删除' : '加入回收站' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <el-dialog :visible.sync="courseAddVisible" title="新增课程" center width="60%" append-to-body>
      <el-form ref="formValidate" v-loading="fullscreenLoading" class="formValidate mt20" :rules="ruleValidate"
               :model="formValidate" label-width="120px"
      >
        <el-row :gutter="24">
          <el-col v-bind="grid2">
            <el-form-item label="课程名称：" prop="name">
              <el-input v-model="formValidate.name" maxlength="249" placeholder="请输入课程名称" :disabled="isDisabled"/>
            </el-form-item>
          </el-col>

          <el-col v-bind="grid2">
            <el-form-item label="课程分类：" prop="cateId">
              <el-cascader v-model="formValidate.cateId" :options="merCateList" :props="props2" clearable
                           class="selWidth" :show-all-levels="false" :disabled="isDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="课程标签：" prop="name">
              <el-tag
                :key="item.label"
                v-for="item in courseLabelList"
                closable
                :disable-transitions="false"
                @close="removeLabel(item)">
                {{item.label}}
              </el-tag>
              <el-button v-if="courseLabelList.length<=3" class="button-new-tag" size="small" @click="showTagDialog">+ 添加标签</el-button>

              <!--                <el-input v-model="courseLabelList" maxlength="249" placeholder="请输入课程名称" :disabled="isDisabled"/>-->
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="副标题：" prop="subName">
              <el-input v-model="formValidate.subName" maxlength="249" placeholder="请输入副标题" :disabled="isDisabled"/>

              <!--              <el-input v-model="formValidate.description" type="textarea" maxlength="250" :rows="3"-->
<!--                        placeholder="请输入商品简介" :disabled="isDisabled"/>-->
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="课程封面图：" prop="image">
              <div class="upLoadPicBox" @click="modalPicTap('1')" :disabled="isDisabled">
                <div v-if="formValidate.image" class="pictrue"><img :src="formValidate.image"></div>
                <div v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont"/>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程详情：" prop="description">
              <ueditor-from v-model="formValidate.description" :content="formValidate.description" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm('formValidate') ">取 消</el-button>
            <el-button type="primary" @click="saveCourse">确 定</el-button>
          </span>
    </el-dialog>
    <el-dialog title="添加标签" center width="480px" append-to-body :visible.sync="tagDialog.visible">
      <el-form :model="tagDialog.form">
        <el-row :gutter="24">
          <el-col v-bind="grid3">
            <el-form-item label="标签名称" :label-width="120" style="display: flex">
              <el-input v-model="tagDialog.form.label" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid3">
            <el-form-item label="标签类型" :label-width="120">
              <el-select v-model="tagDialog.form.labelType" placeholder="请选择标签类型">
                <el-option label="年龄" value="age"></el-option>
                <el-option label="工具" value="tool"></el-option>
                <el-option label="章节数" value="list_count"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tagDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="comfirmTag">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  productLstApi,
  productDeleteApi,
  categoryApi,
  putOnShellApi,
  offShellApi,
  productHeadersApi,
  productExportApi,
  restoreApi,
  productExcelApi
} from '@/api/store'
import { courseLstApi, addCourseApi, courseDeleteApi, onlineOffApi,recycleCourseApi } from '@/api/course'
import { getToken } from '@/utils/auth'
import { checkPermi } from '@/utils/permission' // 权限判断函数
const courseForm = {
  name: '',
  subName:'',
  cateId: '',
  description: '',
  sort: 0,
  image: '',
  imageAttId: ''
}
export default {
  name: 'ProductList',
  data() {
    return {
      courseAddVisible: false,
      props: {
        children: 'child',
        label: 'name',
        value: 'id',
        emitPath: false,
        checkStrictly: true
      },
      // roterPre: roterPre,
      headeNum: [{name:"课程",type:'1'},{name:"课程回收站",type:'5'}],
      listLoading: true,
      tableData: {
        data: [],
        total: 0
      },
      tableFrom: {
        page: 1,
        limit: 20,
        cateId: '',
        name: '',
        type: '1'
      },
      categoryList: [],
      merCateList: [],
      objectUrl: process.env.VUE_APP_BASE_API,
      fullscreenLoading: false,
      ruleValidate: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        cateIds: [
          { required: true, message: '请选择课程分类', trigger: 'change', type: 'array', min: '1' }
        ],
        description: [
          { required: true, message: '课程简介不能为空', trigger: 'blur' }
        ],
        subName:[
          { required: true, message: '副标题不能为空', trigger: 'blur' }
        ]

      },

      formValidate: Object.assign({}, courseForm),
      grid2: {
        xl: 12,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24
      },
      grid3:{
        xl: 24,
        lg: 24,
        md: 24,
        sm: 24,
        xs: 24
      },
      courseLabelList:[],
      tagDialog:{
        visible:false,
        form:{
          label:'',
          labelType:''
        },
        rule:{
          label: [
            { required: true, message: '请输入标签名称', trigger: 'blur' }
          ],
          labelType: [
            { required: true, message: '请选择标签类型', trigger: 'change'}
          ],
        }
      },
      isDisabled: false,
      props2: {
        children: 'child',
        label: 'name',
        value: 'id',
        emitPath: false,
        checkStrictly: true
      }
    }
  },
  mounted() {
    this.getList()
    this.getCategorySelect()
    this.checkedCities = this.$cache.local.has('goods_stroge') ? this.$cache.local.getJSON('goods_stroge') : this.checkedCities
  },
  methods: {

    checkPermi,
    // 点击商品图
    modalPicTap(tit, num, i, status) {
      const _this = this
      if (_this.isDisabled) return
      this.$modalUpload(function(img) {
        if (tit === '1' && !num) {
          _this.formValidate.image = img[0].sattDir
          _this.formValidate.imageAttId = img[0].attId
        }

      }, tit, 'content')
    },
    addCourse() {
      if (this.courseAddVisible == true) {
        this.courseAddVisible = false
      } else {
        this.courseAddVisible = true
      }
    },
    saveCourse() {
      this.listLoading = true
      let obj = this.formValidate
      obj.courseLabelList = this.courseLabelList
      addCourseApi(this.formValidate).then(res => {
        console.info(res)
        this.listLoading = false
        this.resetForm('formValidate')
        this.getList()
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    handleRestore(id) {
      this.$modalSure('恢复课程').then(() => {
        recycleCourseApi({ id:id,isRecycle:false})
          .then((res) => {
            this.$message.success('操作成功')
            this.getList()
          })
      })
    },
    seachList() {
      this.tableFrom.page = 1
      this.getList()
    },
    resetForm(formName) {
      this.courseAddVisible = false
      this.$refs[formName].resetFields()
    },
    // 导出
    exports() {
      productExcelApi({
        cateId: this.tableFrom.cateId,
        name: this.tableFrom.name,
        type: this.tableFrom.type
      }).then((res) => {
        window.location.href = res.fileName
      })
    },
    // 课程分类；
    getCategorySelect() {
      categoryApi({ status: -1, type: 8 }).then(res => {
        this.merCateList = res
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    // 列表
    getList() {
      this.listLoading = true
      courseLstApi(this.tableFrom).then(res => {
        this.tableData.data = res.list
        this.tableData.total = res.total
        this.listLoading = false
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    pageChange(page) {
      this.tableFrom.page = page
      this.getList()
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val
      this.getList()
    },
    // 删除
    handleDelete(id, type) {
      this.$modalSure(`删除 id 为 ${id} 的课程`).then(() => {
        const deleteFlag = type == 5 ? 'delete' : 'recycle'
        courseDeleteApi(id, deleteFlag).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    onchangeIsShow(row) {
      row.isShow
        ? onlineOffApi({ id:row.id,isShow:true}).then(() => {
          this.$message.success('上架成功')
          this.getList()
        }).catch(() => {
          row.isShow = !row.isShow
        }) : onlineOffApi({ id:row.id,isShow:false}).then(() => {
          this.$message.success('下架成功')
          this.getList()
        }).catch(() => {
          row.isShow = !row.isShow
        })
    },


    removeLabel(item){
      let arr = this.courseLabelList,marr=[]
      for(let i in arr){
        if(arr[i].label==item.label&&arr[i].labelType==item.labelType){

        }else{
          marr.push(arr[i])
        }
      }
      this.courseLabelList=marr
    },
    showTagDialog(){
      // this.courseLabelList=[]
      this.tagDialog.form={
        label: '',
        labelType: ''
      }
      this.tagDialog.visible=true
    },
    comfirmTag(){
      if(!this.tagDialog.form.labelType||!this.tagDialog.form.label){
        return
      }
      this.courseLabelList.push({courseId:null,id:null,label:this.tagDialog.form.label,labelType:this.tagDialog.form.labelType})
      this.tagDialog.visible=false
    }

  }
}
</script>

<style scoped lang="scss">
.el-table__body {
  width: 100%;
  table-layout: fixed !important;
}

.taoBaoModal {
  //  z-index: 3333 !important;
}

.demo-table-expand {
  ::v-deep label {
    width: 82px;
  }
}

.demo-table-expand {
  ::v-deep .el-form-item__content {
    width: 77%;
  }
}

.selWidth {
  width: 350px !important;
}

.seachTiele {
  line-height: 30px;
}

.relative {
  position: relative;
}
</style>
